from sqlalchemy import Column, String, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from init.mysql import engine

Base = declarative_base()


class StockRealtime(Base):
    __tablename__ = 'stock_realtime'
    id = Column(Integer, primary_key=True, autoincrement=True)
    dm = Column(String(10))
    h = Column(String(10))
    l = Column(String(10))
    o = Column(String(10))
    pc = Column(String(10))
    p = Column(String(10))
    cje = Column(String(20))
    ud = Column(String(10))
    v = Column(Integer)
    yc = Column(String(10))
    t = Column(String(20))

    def __init__(self, dm, h, l, o, pc, p, cje, ud, v, yc, t):
        self.dm = dm
        self.h = h
        self.l = l
        self.o = o
        self.pc = pc
        self.p = p
        self.cje = cje
        self.ud = ud
        self.v = v
        self.yc = yc
        self.t = t

    @staticmethod
    def not_exist_insert(code, data):
        session = sessionmaker(bind=engine)()
        existing_stock_fiber = session.query(StockRealtime).filter_by(dm=code, t=data['t']).first()
        if existing_stock_fiber:
            return
        else:
            session.add(StockRealtime(dm=code, h=data['h'], l=data['l'], o=data['o'], pc=data['pc'], p=data['p'],
                               cje=data['cje'], ud=data['ud'], v=data['v'], yc=data['yc'], t=data['t']))
        session.commit()
        session.close()


Base.metadata.create_all(engine)
